﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using FineUI;
using SDLITS.Common;
using SDLITS.Model;
using MySoft.Data;
namespace SDLITS.Web.Customer
{
    public partial class ContractChange : CommonBase
    {
        #region 页面初始化
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindArea();
                LoadData();
            }
        }
        #endregion
        protected void BindArea()
        {
            List<Area> lists = SDDbSession.Default.From<Area>().ToList();
            drp_area.DataSource = lists;
            drp_area.DataTextField = "AreaName";
            drp_area.DataValueField = "AreaID";
            drp_area.DataBind();
        }
        #region 读取数据


        private void LoadData()
        {
            int id = 0;
            if (!string.IsNullOrEmpty(Request["id"]))
            {
                id = int.Parse(Request["id"]);
            }
            if (id > 0)
            {
                Contract Tm =null;
                if (SDDbSession.Default.From<Contract>().Where(Contract._.CompanyID == id && Contract._.StatusID == 1).Count() > 0)
                {
                    Tm = SDDbSession.Default.From<Contract>().Where(Contract._.CompanyID == id && Contract._.StatusID == 1).OrderBy(Contract._.CreateDate.Desc).ToFirst();
                }
                else
                {
                    Tm = SDDbSession.Default.From<Contract>().Where(Contract._.CompanyID == id).OrderBy(Contract._.CreateDate.Desc).ToFirst();
                }
                Expense exp=SDDbSession .Default .From <Expense >().Where (Expense._.CompanyID==Tm.CompanyID&&Expense._.ExpenseTypeID==2).ToFirst();
                drp_area.SelectedValue = SDDbSession.Default.From<Room>().Where(Room._.RoomID == Tm.RoomID).ToFirst().AreaID.ToString();
                BindRoom(drp_area.SelectedValue);
                drp_room.SelectedValue = Tm.RoomID.ToString();
                hidroom.Text = Tm.RoomID.ToString();

                txt_comvol.Text = Tm.CompanyCardVol.ToString();
                txt_contractor.Text = Tm.Contractor;
                txt_no.Text = DateTime.Now.ToString("yyyyMMddHHmmss");
                txt_note.Text = Tm.Note;
                txt_phone.Text = Tm.Phone;
                txt_rent.Text = Tm.Rent.ToString();
                txt_rentmanage.Text = Tm.RentManage;
                txt_softvol.Text = Tm.SoftCardVol.ToString();
                txt_start.SelectedDate = Tm.EndDate;
                hidend.Text = Tm.EndDate.ToString();
                txt_elec.Text = exp.PreMonthAmount.ToString();
            }
        }
        #endregion

        #region 保存数据
        protected void btnSaveRefresh_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(drp_room.SelectedValue))
            {
                Alert.Show("没有选择房间！");
                return;
            }
            int returnvalue = 0;
            int id = int.Parse(Request["id"]);
            
            if (Convert.ToDateTime(hidend.Text) >= Convert.ToDateTime(txt_start.Text))
            {
                Alert.Show("企业合同续签日期必须大于当前合同结束日期！");
                return;
            }
            ModelLoginUser user = Session["LoginUser"] as ModelLoginUser;
            int staid = GetNewStatusID(id);
            Contract con = new Contract();
            con.DeAttach();
            con.ContractNo = txt_no.Text;
            con.CompanyID = id;
            con.StatusID = staid;
            con.Contractor = txt_contractor.Text;
            con.Phone = txt_phone.Text;
            con.StartElecFee = int.Parse(txt_elec.Text);
            con.RoomID = int.Parse(drp_room.SelectedValue);
            con.StartDate = DateTime.Parse(txt_start.Text);
            con.EndDate = DateTime.Parse(txt_end.Text);
            con.Rent = txt_rent.Text;
            con.CompanyCardVol = int.Parse(txt_comvol.Text);
            con.SoftCardVol = int.Parse(txt_softvol.Text);
            con.Note = txt_note.Text;
            con.CreateDate = DateTime.Now;
            con.CreateUserID = user.UserID;
            con.RentManage = txt_rentmanage.Text;
            returnvalue = SDDbSession.Default.Insert<Contract>(con);

            if (returnvalue > 0)
            {
                // 如果合同为正常状态更新 Room, Expense, Company 等相关信息
                if (staid == 1)
                {
                    if (!string.IsNullOrEmpty(hidroom.Text) && drp_room.SelectedValue != hidroom.Text)
                    {
                        SDDbSession.Default.Update<Room>(Room._.StatusID, 1, Room._.RoomID == hidroom.Text);
                    }
                    SDDbSession.Default.Update<Room>(Room._.StatusID, 2, Room._.RoomID == drp_room.SelectedValue);

                    SDDbSession.Default.FromSql("Update [Company] Set StatusID=1,RoomID=(select top 1 ct.RoomID from [Contract] ct where ct.CompanyID="+id+" order by ct.CreateDate Desc) Where CompanyID="+id).ExecuteNonQuery();
                    SDDbSession.Default.FromSql("Update [User] Set StatusID=1 Where CompanyID="+id).ExecuteNonQuery();

                    SDDbSession.Default.FromSql("UPDATE [MemCard] SET [StartDate] = '" + txt_start.Text + "', [ExpireDate] = '" + txt_end.Text + "' WHERE [CompanyID] = " + id).ExecuteNonQuery();
                    InitExpense(id, Convert.ToDateTime(txt_start.Text), Convert.ToDateTime(txt_end.Text), int.Parse(txt_elec.Text), txt_rent.Text);
                    
                }
                PageContext.RegisterStartupScript(ActiveWindow.GetHideRefreshReference());
            }
        }
        #endregion

        protected void TextBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindRoom(drp_area.SelectedValue);
        }
        protected void BindRoom(string aid)
        {
            List<Room> list = SDDbSession.Default.From<Room>().Where(Room._.AreaID == aid).ToList();
            drp_room.DataSource = list;
            drp_room.DataTextField = "RoomName";
            drp_room.DataValueField = "RoomID";
            drp_room.DataBind();
        }
        private int GetNewStatusID(int cid)
        {
            int count=SDDbSession.Default.From<Contract>().Where(Contract._.CompanyID == cid && Contract._.StatusID == 1).Count();
            if (count > 0)
                return 2;
            else
                return 1;
        }
        public void InitExpense(int companyID, DateTime? startDate, DateTime? endDate, int preMonthAmoun, string rent)
        {
            decimal rentPrice = 0;
            if (!string.IsNullOrEmpty(rent))
            {
                rentPrice = Convert.ToDecimal(rent);
            }
            do
            {
                if (startDate != null && endDate != null)
                {
                    Expense exp = new Expense();
                    exp.DeAttach();
                    exp.ExpenseTypeID = 2;
                    exp.CompanyID = companyID;
                    exp.ExpenseYear = startDate.Value.Year;
                    exp.ExpenseMonth = startDate.Value.Month;
                    exp.PreMonthAmount = preMonthAmoun;
                    exp.SinglePrice = SDDbSession.Default.From<MasterDic>().ToFirst().ElecPrice;
                    exp.StatusID = 2;
                    SDDbSession.Default.Insert<Expense>(exp);

                    startDate = startDate.Value.AddMonths(1);
                    preMonthAmoun = 0;
                }
            } while (startDate < endDate);
        }
    }
}